package edu.jmu.transmissionassistant.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.yanzhenjie.andserver.AndServer
import com.yanzhenjie.andserver.Server
import edu.jmu.transmissionassistant.component.AppConfig
import edu.jmu.transmissionassistant.component.ServerManager
import edu.jmu.transmissionassistant.util.Logger
import edu.jmu.transmissionassistant.util.NetUtils
import java.net.InetAddress
import java.util.concurrent.TimeUnit

/**
 *  AndServer 后台进程
 */
class CoreService : Service() {
    private lateinit var mServer: Server

    override fun onCreate() {
        mServer = AndServer.webServer(this)
            .port(AppConfig.PORT)
            .timeout(AppConfig.TIME_OUT, TimeUnit.SECONDS)
            .listener(object : Server.ServerListener {
                override fun onStarted() {
                    val address: InetAddress = NetUtils.localIPAddress!!
                    Logger.i("Server start")
                    ServerManager.onServerStart(this@CoreService, address.hostAddress)
                }
                override fun onStopped() {
                    Logger.i("Server stop")
                    ServerManager.onServerStop(this@CoreService)
                }
                override fun onException(e: Exception) {
                    e.printStackTrace()
                    ServerManager.onServerError(this@CoreService, e.message)
                }
            })
            .build()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startServer()
        return START_STICKY
    }

    override fun onDestroy() {
        stopServer()
        super.onDestroy()
    }

    /**
     * Start server.
     */
    private fun startServer() {
        mServer.startup()
    }

    /**
     * Stop server.
     */
    private fun stopServer() {
        mServer.shutdown()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}